//
//  DetailsView.m
//
//  Created by sid on 04/05/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "DetailsView.h"
#import "DNDzgzAppDelegate.h"

@implementation DetailsView

@synthesize hud;
@synthesize alertView;

- (void) viewDidLoad
{
	NSLog(@"viewDidLoad");
	[super viewDidLoad];
	[favoritesButton setImage:[UIImage imageNamed:@"fav.png"]];
	[locateButton setImage:[UIImage imageNamed:@"eye.png"]];
	
	if ([self inFavorites])
	{
		NSLog(@"In favorites");
		[favoritesButton setEnabled:NO];
	}

	NSLog(@"end viewDidLoad");
}

- (BOOL)inFavorites
{
	NSLog(@"checkIfExistsStationInDefaults");
	NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
	/*
	[userDefaults removeObjectForKey:@"myFavorites"];
	[userDefaults synchronize];
	 */
	
	NSDictionary *favItems = [userDefaults dictionaryForKey:@"myFavorites"];
	if (favItems == nil) return NO;
	
	NSString *key = [annotation newGetKey];
	BOOL exist = [favItems objectForKey:key] != nil;
	[key release];
	NSLog(@"end checkIfExistsStationInDefaults");
	return exist;
}

- (IBAction)addToFavorites
{
	NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
	
	NSMutableDictionary *mutableFavs = nil;
	NSDictionary *favs = [userDefaults dictionaryForKey:@"myFavorites"];
	if ((favs == nil) || ([favs count] == 0)) {
		mutableFavs = [[NSMutableDictionary alloc] init];
	} else {
		mutableFavs = [[NSMutableDictionary alloc] initWithDictionary:favs];
	}
	
	NSString *key = [annotation newGetKey];
	NSMutableDictionary *ann = [[NSMutableDictionary alloc] init];
	[annotation save:ann];
	[mutableFavs setObject:ann forKey:key];
	NSLog(@"Added favorite for key %@", key);
	[key release];
	[ann release];
	
	[userDefaults setObject:mutableFavs forKey:@"myFavorites"];
	[userDefaults synchronize];
	
	favoritesButton.enabled = NO;
	[mutableFavs release];
}

- (IBAction)showDirections
{
	/*
	DirectionsViewController *controller = [[DirectionsViewController alloc] initWithAnnotation:annotation];
	[self.navigationController pushViewController:controller animated:YES];
	[controller release];
	*/

	
	MapDirectionsViewController *controller = [[MapDirectionsViewController alloc] initWithEndPoint:annotation];
	[self.navigationController pushViewController:controller animated:YES];
	//[controller release];
}

- (void)setAnnotation:(MyAnnotation *) _annotation
{
	toolbar.userInteractionEnabled = NO;
	items = [NSMutableArray new];
	NSLog(@"setAnnotation");
	annotation = _annotation;
	[annotation retain];
	self.title = annotation.title;
	[self setSearchingStatus:YES];
	responseData = [[NSMutableData data] retain];
	NSString* url = [NSString stringWithFormat:@"http://2.latest.dnd-zgz.appspot.com/point?service=%@&id=%@", annotation.service, annotation.identifier];
	NSLog(@"%@", url);
	NSURLRequest* request = [NSURLRequest requestWithURL: [NSURL URLWithString:url]];
	[[NSURLConnection alloc] initWithRequest:request delegate:self];
	NSLog(@"end setAnnotation");
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{
	[responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{
	[responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{
	alertView = [[UIAlertView alloc] initWithTitle:@"Error de conexión"
														message:@"Compruebe que está conectado a Internet e inténtelo de nuevo."
													   delegate:nil
											  cancelButtonTitle:@"Aceptar"
											  otherButtonTitles:nil];	
	[alertView show];
	[connection release];
	[responseData release];
	[self setSearchingStatus:NO];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
	[self.navigationController popViewControllerAnimated:YES];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{
	NSLog(@"connectionDidFinishLoading");
	[connection release];
	NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
	[responseData release];
	
	NSDictionary* data = [[NSDictionary alloc] initWithDictionary:[responseString JSONValue]];
	NSArray *itemsArray = [[NSArray alloc] initWithArray:[data objectForKey:@"items"]];
	
	for(int i = 0; i < [itemsArray count]; i++) 
	{
		NSLog(@"%@", [itemsArray objectAtIndex:i]);
		[items addObject:[itemsArray objectAtIndex:i]];
	}
	
	[itemsArray release];
	[responseString release];
	[data release];
	
	[tableViewCell reloadData];
	[self setSearchingStatus:NO];
	NSLog(@"end connectionDidFinishLoading");
}

#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{
	return [items count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	NSArray *subitems = [items objectAtIndex:indexPath.row];
	
	UITableViewCellStyle style;
	NSString *cellIdentifier = nil;
	
	if ([subitems count] > 1) {
		cellIdentifier = @"subtitle";
		style = UITableViewCellStyleSubtitle;
	} else {
		cellIdentifier = @"default";
		style = UITableViewCellStyleDefault;
	}

	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
	if(cell == nil) {
		cell = [[[UITableViewCell alloc] initWithStyle:style reuseIdentifier:cellIdentifier] autorelease];
	}
	cell.textLabel.text = [subitems objectAtIndex:0];
	if ([subitems count] > 1) {
		cell.detailTextLabel.text = [subitems objectAtIndex:1];
	}
	cell.selectionStyle = UITableViewCellSelectionStyleNone;
	
#if (__IPHONE_OS_VERSION_MAX_ALLOWED >= 30200)
	
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) 
	{
		cell.textLabel.font = [UIFont boldSystemFontOfSize:30];
    } 	
	
#endif 
	return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{	
#if (__IPHONE_OS_VERSION_MAX_ALLOWED >= 30200)
	
	
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) 
	{
        return 80;
    } 	
    else 
	{
		return 55;
	}
	
	
#endif
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
	return annotation.subtitle;
}

- (void)setSearchingStatus:(BOOL)isSearching
{
	//when network action, toggle network indicator and activity indicator
	if (isSearching) {
		[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
		
		UIWindow *window = [UIApplication sharedApplication].keyWindow;
		hud = [[MBProgressHUD alloc] initWithWindow:window];
		[window addSubview:hud];
		hud.labelText = @"Cargando...";
		[hud show:YES];
		toolbar.userInteractionEnabled = NO;
	} else {
		[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
		
		[hud hide:YES];
		[hud removeFromSuperview];
		[hud release];
		toolbar.userInteractionEnabled = YES;
	}	
}

#pragma mark -
#pragma mark MBProgressHUDDelegate methods

- (void)hudWasHidden 
{
    // Remove HUD from screen when the HUD was hidded
    [hud removeFromSuperview];
    [hud release];
	toolbar.userInteractionEnabled = YES;
}

- (BOOL)containsString:(NSString *)aString inOriginalNSSString:(NSString *)originalStr
{
	NSRange range = [[originalStr lowercaseString] rangeOfString:[aString lowercaseString]];
	
	if (range.location != NSNotFound) 
	{
		return YES;
	}
	else 
	{
		return NO;
	}
}

- (void) dealloc
{
	DNDzgzAppDelegate *delegateVariable = (DNDzgzAppDelegate *)[UIApplication sharedApplication].delegate;
	NSString *service = delegateVariable.service;
	
	if([self containsString:@"bus" inOriginalNSSString:service])
	{
		NSLog(@"preloaded antes de asignar: %@", delegateVariable.preLodadedBus);
		delegateVariable.preLodadedBus = @"NO";
		NSLog(@"preloaded despues de asignar: %@", delegateVariable.preLodadedBus);
	}
	else if([self containsString:@"bizi" inOriginalNSSString:service])
	{
		NSLog(@"preloaded antes de asignar: %@", delegateVariable.preLodadedBizi);
		delegateVariable.preLodadedBizi = @"NO";
		NSLog(@"preloaded despues de asignar: %@", delegateVariable.preLodadedBizi);
	}
	else if([self containsString:@"wifi" inOriginalNSSString:service])
	{
		NSLog(@"preloaded antes de asignar: %@", delegateVariable.preLodadedWifi);
		delegateVariable.preLodadedWifi = @"NO";
		NSLog(@"preloaded despues de asignar: %@", delegateVariable.preLodadedWifi);
	}

	[alertView release];
	[items release];
	[annotation release];
	[super dealloc];
}

@end